#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import shutil
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn

OMIT_PATH = False

class ProxyRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        fpath = '.' + self.path
        if OMIT_PATH:
            fpath = os.path.basename(fpath)
        if os.path.exists(fpath):
            fsize = os.path.getsize(fpath)
            with open(fpath, 'rb') as f:
                self.send_response(200)
                self.send_header("Content-Length", str(fsize))
                self.end_headers()

                shutil.copyfileobj(f, self.wfile)
        else:
            self.send_error(404)


class ProxyServer(ThreadingMixIn, HTTPServer):
    def __init__(self, server_address, bind_and_activate=True):
        ProxyRequestHandler.protocol_version = "HTTP/1.1"
        HTTPServer.__init__(self, server_address, ProxyRequestHandler, bind_and_activate)


if __name__ == "__main__":
    server_addr = ("", 8180)

    if len(sys.argv) > 1:
        opt_index = 1
        if sys.argv[1] == '-h':
            print "Usage %s [--omit-path] [[listen_addr:]listen_port]" % sys.argv[0]
            sys.exit()
        elif sys.argv[1] == '--omit-path':
            OMIT_PATH = True
            opt_index = 2

        opt_addr = sys.argv[opt_index]
        if ':' in opt_addr:
             addr, _, port = opt_addr.partition(':')
             server_addr = (addr, int(port))
        else:
             server_addr = ("", int(opt_addr))

    print "listen on %s" % str(server_addr)
    httpd = ProxyServer(server_addr)
    httpd.serve_forever()
